const express = require('express');
const router = express.Router();

const sendMail = require('../../utils/email.js');
const { generateRandomSixDigitNumber } = require('../../utils/utlis.js');
const { getKey, setKey, delKey } = require('../../utils/redis.js');
const { v4: uuidv4 } = require('uuid');
const { no, ok } = require('../../utils/utlis');

router.post('/code', async (req, res, next) => {
	try {
		let { email } = req.body;
		if (!email) throw new Error('邮箱不能为空');
		let code = generateRandomSixDigitNumber();
		let uuid = uuidv4();
		// 存入redis 验证码
		await setKey(uuid, code, 120);

		await sendMail(email, code);

		res.send(ok({ captchaKey: uuid }));
	} catch (error) {
		res.send(no(error.message));
	}
});

module.exports = router;
